<template>
  <div class="profile-container">
    <!-- 左侧固定导航 -->
    <div class="profile-sidebar" role="complementary">
      <!-- 用户信息卡片 -->
      <el-card class="user-card">
        <div class="avatar-section">
          <div class="avatar-wrapper" @click="showCropper = true" role="button" tabindex="0" aria-label="更换头像">
            <!-- <el-avatar :size="100" :src="getAvatarUrl" alt="用户头像"></el-avatar> -->
            <el-avatar :size="100" :src="userInfo.avatar" alt="用户头像"></el-avatar>
            <div class="upload-overlay" inert>
              <i class="el-icon-camera"></i>
            </div>
          </div>
        </div>
        <h3 class="username">{{ userInfo.nickname }}</h3>
        <p class="signature">{{ userInfo.signature || '这个人很懒，还没有写简介...' }}</p>

        <!-- 添加签到按钮 -->
        <div class="sign-in-section">
          <el-button type="primary" :disabled="signInStatus" @click="handleSignIn" size="small"
            :loading="signInLoading">
            <i class="el-icon-check"></i>
            {{ signInStatus ? '今日已签到' : '立即签到' }}
          </el-button>
          <div class="sign-in-stats">
            <div class="stat-item">
              <span class="label">连续签到</span>
              <span class="value">{{ signInStats.continuousDays }}天</span>
            </div>
            <div class="stat-item">
              <span class="label">累计签到</span>
              <span class="value">{{ signInStats.totalDays }}天</span>
            </div>
          </div>
        </div>

        <div class="user-stats" role="list">
          <div class="stat-item" role="listitem">
            <span class="number">{{ statistics.posts }}</span>
            <span class="label">文章</span>
          </div>
          <div class="stat-item" role="listitem">
            <span class="number">{{ statistics.followers }}</span>
            <span class="label">关注者</span>
          </div>
          <div class="stat-item" role="listitem">
            <span class="number">{{ statistics.likes }}</span>
            <span class="label">获赞</span>
          </div>
        </div>
      </el-card>

      <!-- 导航菜单 -->
      <el-menu class="nav-menu" :default-active="currentTab" @select="currentTab = $event" role="navigation">
        <el-menu-item v-for="tab in tabs" :key="tab.key" :index="tab.key" :aria-label="tab.label">
          <i :class="tab.icon"></i>
          <span>{{ tab.label }}</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧内容区 -->
    <main class="content-area" role="main">
      <!-- 个人资料 -->
      <div v-if="currentTab === 'profile'" class="content-section">
        <h2 class="section-title">个人资料</h2>
        <el-form ref="profileForm" :model="profileForm" :rules="profileRules" label-width="80px" class="profile-form"
          @submit.prevent="submitProfile">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="profileForm.nickname" placeholder="请输入昵称" aria-label="昵称输入框"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="profileForm.email" placeholder="请输入邮箱" aria-label="邮箱输入框"></el-input>
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input type="textarea" v-model="profileForm.signature" :rows="4" placeholder="介绍一下自己吧..."></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="profileForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitProfile" :loading="loading" icon="el-icon-edit"
              size="small">保存修改</el-button>
            <el-button size="small" @click="resetProfile" icon="el-icon-refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 账号绑定 -->
      <div v-if="currentTab === 'binding'" cla1110ss="content-section">
        <h2 class="section-title">账号绑定</h2>
        <div class="binding-tips">
          <el-alert title="账号绑定提示" type="info" description="绑定第三方账号后，您可以直接使用第三方账号登录本站，还可以同步您的个人信息。" show-icon
            :closable="false">
          </el-alert>
        </div>
        <div class="binding-list">
          <el-card v-for="account in boundAccounts" :key="account.type" class="binding-item">
            <div class="binding-content">
              <div class="account-info">
                <div class="account-icon">
                  <i :class="account.icon" :style="{ color: account.color }"></i>
                </div>
                <div class="account-details">
                  <span class="account-name">{{ account.name }}</span>
                  <span class="account-desc">{{ account.isBound ? account.username : '未绑定账号' }}</span>
                </div>
              </div>
              <div class="binding-status">
                <el-tag :type="account.isBound ? 'success' : 'info'" size="small" effect="dark" class="status-tag">
                  {{ account.isBound ? '已绑定' : '未绑定' }}
                </el-tag>
                <el-button :type="account.isBound ? 'danger' : 'primary'" size="small"
                  :icon="account.isBound ? 'el-icon-close' : 'el-icon-link'"
                  @click="account.isBound ? unbindAccount(account.type) : bindAccount(account.type)">
                  {{ account.isBound ? '解除绑定' : '立即绑定' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

      </div>

      <!-- 我的文章 -->
      <div v-if="currentTab === 'posts'" class="content-section">
        <h2 class="section-title">我的文章</h2>
        <div class="action-bar">
          <div>
            <el-input v-model="params.title" size="mini" placeholder="输入文字标题搜索文章..." prefix-icon="el-icon-search"
              style="width: 300px;margin-right: 10px"></el-input>
            <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          </div>

          <el-button type="primary" icon="el-icon-edit" size="mini" @click="$router.push('/editor')">写文章</el-button>
        </div>

        <div v-loading="loading" v-if="posts.length">
          <el-card v-for="post in posts" :key="post.id" class="post-item">
            <div class="post-content">
              <h3 class="post-title" @click="viewPost(post.id)">
                {{ post.title }}
                <el-tag v-if="post.status === 2" size="small" type="info">草稿</el-tag>
                <el-tag v-else-if="post.status === 0" size="small" type="warning">待审核</el-tag>
                <el-tag v-else-if="post.status === 1" size="small" type="success">已发布</el-tag>
              </h3>
              <p class="post-excerpt">{{ post.summary }}</p>
              <div class="post-meta">
                <el-tag size="small"><i class="el-icon-date"></i>{{ post.createTime }}</el-tag>
                <el-tag size="small" type="info"><i class="el-icon-view"></i>{{ post.quantity }} 阅读</el-tag>
                <el-tag size="small" type="success"><i class="el-icon-chat-line-square"></i>{{ post.commentNum || 0 }}
                  评论</el-tag>
                <el-tag size="small" type="warning">
                  <i class="far fa-heart" style="color:rgb(191, 53, 85);"></i>
                  {{ post.likeNum || 0 }} 点赞</el-tag>
              </div>
            </div>
            <div class="post-actions">
              <el-button type="text" icon="el-icon-view" @click="viewPost(post.id)">查看</el-button>
              <el-button type="text" icon="el-icon-edit" @click="editPost(post.id)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" class="delete" @click="deletePost(post)">删除</el-button>
            </div>
          </el-card>

          <div class="pagination-box">
            <el-pagination background @current-change="handlePostChange" :current-page="params.pageNum"
              :page-size="params.pageSize" :total="total" layout="prev, pager, next" class="pagination"></el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无文章，快去发布你的文章吧~~"></el-empty>
      </div>

      <div v-if="currentTab === 'moments'" class="content-section">
        <h2 class="section-title">我的说说</h2>
        <div v-if="myMoments.length" v-loading="loading">
          <el-card v-for="moment in myMoments" :key="moment.id" class="moment-item">
            <div class="moment-content" @click="viewMoment(moment.id)">
              <p class="moment-text" v-html="parseContent(moment.content)"></p>

              <!-- 说说图片展示 -->
              <div class="moment-images" v-if="moment.images && moment.images !== ''">
                <!-- 限制最多显示9张图片 -->
                <div v-for="(img, index) in parseImages(moment.images).slice(0, 9)" :key="index" class="image-container"
                  @click="previewImage(parseImages(moment.images), index)">
                  <img v-lazy="img" :key="img" alt="说说图片" />
                </div>
              </div>
              <!-- <div class="moment-images" v-if="moment.images">
                <div v-for="(img, index) in parseImages(moment.images)" :key="index" class="image-container" @click="previewImage(parseImages(moment.images), index)">
                  <img v-lazy="img" :key="img" alt="说说图片" />
                </div>
              </div> -->

              <div class="moment-meta">
                <div class="time-tag">
                  <el-tag size="small"
                    :type="moment.updateTime && moment.updateTime !== moment.createTime ? 'warning' : 'info'"
                    class="time-tag-item">
                    <i
                      :class="moment.updateTime && moment.updateTime !== moment.createTime ? 'el-icon-refresh' : 'el-icon-time'"></i>
                    {{ moment.updateTime && moment.updateTime !== moment.createTime ? '更新于 ' +
                      formatTime(moment.updateTime) : formatTime(moment.createTime) }}
                  </el-tag>
                </div>
                <el-tag size="small" type="success" v-if="moment.likeCount > 0">
                  <i class="far fa-heart"></i>
                  {{ moment.likeCount }} 赞
                </el-tag>
                <el-tag size="small" type="info" v-if="moment.commentCount > 0">
                  <i class="el-icon-chat-line-square" style="color: #409EFF;"></i>
                  {{ moment.commentCount }} 评论
                </el-tag>
              </div>
            </div>
            <div class="moment-actions">
              <el-button type="text" icon="el-icon-edit" @click="editMoment(moment)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" class="delete"
                @click="deleteMomentConfirm(moment.id)">删除</el-button>
            </div>
          </el-card>

          <div class="pagination-box">
            <el-pagination background @current-change="handleMomentPageChange" :current-page="momentParams.pageNum"
              :page-size="momentParams.pageSize" layout="prev, pager, next" :total="momentTotal">
            </el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无说说数据"></el-empty>
      </div>

      <!-- 我的评论 -->
      <div v-if="currentTab === 'comments'" class="content-section">
        <h2 class="section-title">我的评论</h2>
        <div v-if="myComments.length" v-loading="loading">
          <el-card v-for="comment in myComments" :key="comment.id" class="comment-item">
            <div class="comment-actions">
              <p class="comment-text" v-html="parseContent(comment.content)"></p>
              <el-button type="text" icon="el-icon-delete" class="delete"
                @click="deleteComment(comment.id)">删除</el-button>
            </div>
            <div class="comment-meta">
              <!-- 根据评论类型显示不同的链接 -->
              <template v-if="comment.articleId">
                <el-link type="primary" @click="viewPost(comment.articleId)">
                  文章：{{ comment.articleTitle || '未知文章' }}
                </el-link>
              </template>
              <template v-else-if="comment.momentId">
                <el-link type="success" @click="viewMoment(comment.momentId)">
                  说说
                </el-link>
              </template>
              <el-tag size="small">
                <i class="el-icon-time"></i>
                {{ comment.createTime }}
              </el-tag>
              <el-tag size="small" type="success">
                <i class="far fa-heart"></i>
                {{ comment.likeCount ? comment.likeCount : 0 }} 赞
              </el-tag>
            </div>
          </el-card>
          <div class="pagination-box">
            <el-pagination background v-if="myComments.length" @current-change="handlePageChange"
              :current-page="params.pageNum" :page-size="params.pageSize" layout="prev, pager, next" :total="total">
            </el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无评论数据"></el-empty>
      </div>

      <!-- 我的回复 -->
      <div v-if="currentTab === 'replies'" class="content-section">
        <h2 class="section-title">我的回复</h2>
        <div v-if="myReplies.length" v-loading="loading">
          <el-card v-for="reply in myReplies" :key="reply.id" class="reply-item">
            <div class="reply-content">
              <div class="comment-actions">
                <p class="reply-text">
                  <el-tag size="small" type="info">回复 @{{ reply.replyNickname }}</el-tag>
                  <span v-html="parseContent(reply.content)"></span>
                </p>
                <el-button type="text" icon="el-icon-delete" class="delete"
                  @click="deleteComment(reply.id)">删除</el-button>
              </div>
              <div class="reply-meta">
                <!-- 根据回复类型显示不同的链接 -->
                <template v-if="reply.articleId">
                  <el-link type="primary" @click="viewPost(reply.articleId)">
                    文章：{{ reply.articleTitle || '未知文章' }}
                  </el-link>
                </template>
                <template v-else-if="reply.momentId">
                  <el-link type="success" @click="viewMoment(reply.momentId)">
                    说说
                  </el-link>
                </template>
                <el-tag size="small">
                  <i class="el-icon-time"></i>
                  {{ reply.createTime }}
                </el-tag>
                <el-tag size="small" type="success">
                  <i class="far fa-heart"></i>
                  {{ reply.likeCount ? reply.likeCount : 0 }} 赞
                </el-tag>
              </div>
            </div>
          </el-card>
          <div class="pagination-box">
            <el-pagination background v-if="myReplies.length" @current-change="handleReplyPageChange"
              :current-page="replyParams.pageNum" :page-size="replyParams.pageSize" layout="prev, pager, next"
              :total="replyTotal">
            </el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无回复数据"></el-empty>
      </div>

      <!-- 我的点赞 -->
      <!-- 修改我的点赞部分的文章卡片结构 -->
      <div v-if="currentTab === 'likes'" class="content-section likes-section">
        <h2 class="section-title">我的点赞</h2>

        <div class="like-type-selector">
          <el-radio-group v-model="likeType" @change="handleLikeTypeChange" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="article">文章</el-radio-button>
            <el-radio-button label="moment">说说</el-radio-button>
            <el-radio-button label="comment">评论</el-radio-button>
          </el-radio-group>
        </div>

        <div v-if="myLikes.length" v-loading="loading">
          <!-- 文章类型的点赞项 -->
          <el-card v-for="like in myLikes" :key="like.id" class="like-item" shadow="hover">
            <template v-if="like.type === 'article'">
              <!-- 上下结构：标题在上，摘要在下 -->
              <div class="article-like-content">
                <h3 class="article-title">
                  <el-link type="primary" @click="viewPost(like.id)">{{ like.title }}</el-link>
                </h3>
                <p class="article-summary">{{ like.content || '暂无摘要' }}</p>
                <div class="like-meta">
                  <el-tag size="small" type="primary">
                    <i class="el-icon-document"></i> 文章
                  </el-tag>
                  <el-tag size="small">
                    <i class="el-icon-time"></i>
                    {{ formatTime(like.createTime) }}
                  </el-tag>
                  <el-tag size="small" type="success">
                    <i class="far fa-heart"></i>
                    {{ like.likeCount ? like.likeCount : 0 }} 赞
                  </el-tag>
                </div>
              </div>
            </template>

            <!-- 说说类型的点赞项 -->
            <template v-else-if="like.type === 'moment'">
              <div class="moment-like-content" @click="viewMoment(like.id)">
                <div class="moment-content">
                  <p v-html="parseContent(like.content)"></p>
                </div>
                <div class="like-meta">
                  <el-tag size="small" type="success">
                    <i class="el-icon-chat-dot-square"></i> 说说
                  </el-tag>
                  <el-tag size="small">
                    <i class="el-icon-time"></i>
                    {{ formatTime(like.createTime) }}
                  </el-tag>
                  <el-tag size="small" type="success">
                    <i class="far fa-heart"></i>
                    {{ like.likeCount ? like.likeCount : 0 }} 赞
                  </el-tag>
                </div>
              </div>
            </template>

            <!-- 评论类型的点赞项 -->
            <template v-else-if="like.type === 'comment'">
              <div class="comment-like-content">
                <div class="comment-content">
                  <p v-html="parseContent(like.content)"></p>
                </div>
                <div class="comment-source" v-if="like.articleId">
                  <el-link type="primary" @click="viewPost(like.articleId)">
                    来自文章：{{ like.articleTitle }}
                  </el-link>
                </div>
                <div class="comment-source" v-else-if="like.momentId">
                  <el-link type="success" @click="viewMoment(like.momentId)">
                    来自说说
                  </el-link>
                </div>
                <div class="like-meta">
                  <el-tag size="small" type="info">
                    <i class="el-icon-chat-line-square"></i> 评论
                  </el-tag>
                  <el-tag size="small">
                    <i class="el-icon-time"></i>
                    {{ formatTime(like.createTime) }}
                  </el-tag>
                  <el-tag size="small" type="success">
                    <i class="far fa-heart"></i>
                    {{ like.likeCount ? like.likeCount : 0 }} 赞
                  </el-tag>
                </div>
              </div>
            </template>
          </el-card>

          <div class="pagination-box">
            <el-pagination background v-if="myLikes.length" @current-change="handleLikePageChange"
              :current-page="likeParams.pageNum" :page-size="likeParams.pageSize" layout="prev, pager, next"
              :total="likeTotal">
            </el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无点赞数据"></el-empty>
      </div>
      <!-- <div v-if="currentTab === 'likes'" class="content-section likes-section">
        <h2 class="section-title">我的点赞</h2>
        
        <div class="like-type-selector">
          <el-radio-group v-model="likeType" @change="handleLikeTypeChange" size="small">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="article">文章</el-radio-button>
            <el-radio-button label="moment">说说</el-radio-button>
            <el-radio-button label="comment">评论</el-radio-button>
          </el-radio-group>
        </div>
        
        <div v-if="myLikes.length" v-loading="loading">
          <el-card v-for="like in myLikes" :key="like.id" class="like-item">
            <div class="like-content">
              <div class="like-actions">
                <template v-if="like.type === 'article'">
                  <h3 class="like-title">
                    <el-link type="primary" @click="viewPost(like.id)">{{ like.title }}</el-link>
                  </h3>
                  <p>{{ like.content }}</p>
                </template>
                
                <template v-else-if="like.type === 'moment'">
                  <div class="like-comment">
                    <el-link type="success" @click="viewMoment(like.id)">
                      <p v-html="parseContent(like.content)"></p>
                    </el-link>
                  </div>
                </template>
                
                <template v-else-if="like.type === 'comment'">
                  <div class="like-comment">
                    <p v-html="parseContent(like.content)"></p>
                    <div class="comment-source" v-if="like.articleId">
                      <el-link type="primary" @click="viewPost(like.articleId)">
                        来自文章：{{ like.articleTitle }}
                      </el-link>
                    </div>
                    <div class="comment-source" v-else-if="like.momentId">
                      <el-link type="success" @click="viewMoment(like.momentId)">
                        来自说说
                      </el-link>
                    </div>
                  </div>
                </template>
              </div>
              
              <div class="like-meta">
                <el-tag size="small" :type="getLikeTypeTag(like.type)">
                  {{ getLikeTypeLabel(like.type) }}
                </el-tag>
                <el-tag size="small">
                  <i class="el-icon-time"></i>
                  {{ like.createTime }}
                </el-tag>
                <el-tag size="small" type="success">
                  <i class="far fa-heart"></i>
                  {{ like.likeCount ? like.likeCount : 0 }} 赞
                </el-tag>
              </div>
            </div>
          </el-card>
          <div class="pagination-box">
            <el-pagination background v-if="myLikes.length" @current-change="handleLikePageChange"
              :current-page="likeParams.pageNum" :page-size="likeParams.pageSize" layout="prev, pager, next" :total="likeTotal">
            </el-pagination>
          </div>
        </div>
        <el-empty v-else description="暂无点赞数据"></el-empty>
      </div> -->

      <!-- 修改密码 -->
      <div v-if="currentTab === 'security'" class="content-section">
        <h2 class="section-title">账号安全</h2>

        <!-- 2FA Section -->
        <div class="security-section">
          <h3 class="sub-title">两步验证 (2FA)</h3>
          <div v-if="userInfo.mfaEnabled" class="mfa-status-card enabled">
            <div class="status-icon">
              <i class="el-icon-success"></i>
            </div>
            <div class="status-text">
              <p class="status-title">两步验证已启用</p>
              <p class="status-desc">您的账户受到额外安全保护。登录时需要验证码。</p>
            </div>
            <el-button type="danger" @click="openDisableMfaDialog" :loading="mfaLoading" size="small">禁用2FA</el-button>
          </div>
          <div v-else class="mfa-status-card disabled">
            <div class="status-icon">
              <i class="el-icon-warning"></i>
            </div>
            <div class="status-text">
              <p class="status-title">两步验证未启用</p>
              <p class="status-desc">添加额外的安全层，以保护您的帐户免受未经授权的访问。</p>
            </div>
            <el-button type="primary" @click="openEnableMfaDialog" :loading="mfaLoading" size="small">启用2FA</el-button>
          </div>
        </div>

        <el-divider></el-divider>

        <h3 class="sub-title">修改密码</h3>
        <div class="binding-tips">
          <el-alert title="修改密码提示" type="info" description="只有邮箱登录的才可修改密码，其他第三方登录不存在修改密码功能。" show-icon
            :closable="false">
          </el-alert>
        </div>
        <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px"
          class="security-form">
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input type="password" v-model="passwordForm.oldPassword" show-password placeholder="请输入当前密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="passwordForm.newPassword" show-password placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input type="password" v-model="passwordForm.confirmPassword" show-password
              placeholder="请再次输入新密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="submitPasswordChange" icon="el-icon-edit"
              :loading="loading">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 反馈 -->
      <div v-if="currentTab === 'feedback'" class="content-section">
        <h2 class="section-title">意见反馈</h2>
        <el-tabs>
          <el-tab-pane label="提交反馈">
            <el-form ref="feedbackForm" :model="feedbackForm" :rules="feedbackRules" label-width="100px"
              class="feedback-form">
              <el-form-item label="反馈类型" prop="type">
                <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型">
                  <el-option v-for="item in feedbackTypes" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="反馈内容" prop="content">
                <el-input type="textarea" v-model="feedbackForm.content" :rows="5"
                  placeholder="请详细描述您的问题或建议..."></el-input>
              </el-form-item>
              <el-form-item label="联系邮箱" prop="email">
                <el-input v-model="feedbackForm.email" placeholder="请留下您的联系邮箱，方便我们回复您"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitFeedback" icon="el-icon-check"
                  :loading="loading">提交反馈</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="我的反馈">
            <div class="feedback-list">
              <div v-loading="loading" v-if="myFeedbacks.length">
                <el-card v-for="feedback in myFeedbacks" :key="feedback.id" class="feedback-item">
                  <div class="feedback-header">
                    <div class="feedback-info">
                      <el-tag v-if="item.value === feedback.type" v-for="item in feedbackTypes" :key="item.value"
                        :type="item.style">
                        {{ item.label }}
                      </el-tag>
                      <span class="feedback-time">
                        <i class="far fa-clock"></i>
                        {{ feedback.createTime }}
                      </span>
                    </div>
                    <el-tag v-if="item.value === String(feedback.status)" v-for="item in feedbackStatus"
                      :key="item.value" :type="item.style">
                      {{ item.label }}
                    </el-tag>
                  </div>
                  <div class="feedback-content">
                    <p>{{ feedback.content }}</p>
                  </div>
                  <div class="feedback-reply" v-if="feedback.replyContent">
                    <div class="reply-title">
                      <i class="el-icon-chat-line-round"></i> 管理员回复：
                    </div>
                    <p class="reply-content">{{ feedback.replyContent }}</p>
                  </div>
                </el-card>
                <div class="pagination-box" v-if="myFeedbacks.length">
                  <el-pagination background @current-change="handleFeedbackPageChange" :current-page="params.pageNum"
                    :page-size="params.pageSize" layout="prev, pager, next" :total="total">
                  </el-pagination>
                </div>
              </div>
              <el-empty v-else description="暂无反馈记录"></el-empty>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

    </main>

    <!-- 编辑说说弹窗 -->
    <el-dialog title="编辑说说" :visible.sync="momentDialogVisible" width="650px" @closed="resetMomentForm" destroy-on-close
      custom-class="moment-dialog">
      <el-form :model="momentForm" ref="momentFormRef" :rules="momentRules" label-width="80px">
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="editorConfig"
              :mode="'default'" />
            <Editor style="height: 300px; overflow-y: auto;" v-model="momentForm.content" :defaultConfig="editorConfig"
              :mode="'default'" @onCreated="onEditorCreated" />
          </div>
        </el-form-item>
        <el-form-item label="图片">
          <div class="upload-tip">
            <i class="el-icon-info"></i>
            <span>最多可上传9张图片，单张图片不超过5MB</span>
          </div>
          <el-upload class="upload-images" action="#" list-type="picture-card" :http-request="uploadMomentImage"
            :on-remove="handleRemoveMomentImage" :on-preview="handlePreviewMomentImage" multiple :limit="9"
            :file-list="momentFileList" :on-exceed="handleExceedMomentImage" accept=".jpg,.jpeg,.png,.gif">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="momentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMomentEdit" :loading="momentSubmitLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <mj-image-preview ref="imagePreview" class="preview-layer" />
    <!-- <el-dialog :visible.sync="previewVisible" title="图片预览" width="60%" custom-class="preview-dialog">
      <img :src="previewUrl" alt="Preview Image" style="width: 100%; object-fit: contain;" />
    </el-dialog> -->

    <AvatarCropper :visible.sync="showCropper" :user="userInfo" @update-avatar="handleAvatarUpdate" />

    <!-- 启用2FA 弹窗 -->
    <el-dialog title="启用两步验证 (2FA)" :visible.sync="mfaEnableDialogVisible" width="700px" @closed="closeEnableMfaDialog"
      destroy-on-close custom-class="mfa-dialog" top="5vh">
      <div v-if="!mfaFeedbackStatus">
        <el-steps :active="mfaSetupStep" finish-status="success" simple style="margin-bottom: 20px">
          <el-step title="了解2FA"></el-step>
          <el-step title="扫描二维码"></el-step>
          <el-step title="验证并启用"></el-step>
        </el-steps>

        <div v-loading="mfaLoading">
          <!-- 步骤一：了解2FA -->
          <div v-if="mfaSetupStep === 1" class="setup-step">
            <MfaGuide />
            <div class="setup-actions">
              <el-button type="primary" @click="goToMfaStep(2)">下一步</el-button>
            </div>
          </div>

          <!-- 步骤二：扫描二维码 -->
          <div v-if="mfaSetupStep === 2" class="setup-step">
            <div class="qr-code-section">
              <h3 class="section-subtitle">扫描QR码</h3>
              <p class="section-description">
                使用您的身份验证器应用扫描下方的二维码，将本网站添加到您的验证器中。
              </p>

              <div class="qr-code-container">
                <el-image :src="mfaSetupData.qrCode" alt="QR Code" class="qr-code-image"></el-image>
              </div>

              <div class="manual-entry">
                <el-collapse>
                  <el-collapse-item title="无法扫描？点击此处手动输入" name="1">
                    <div class="manual-key">
                      <p>如果无法扫描QR码，您可以在验证器应用中手动输入以下密钥：</p>
                      <div class="secret-key-wrapper">
                        <code class="secret-key">{{ mfaSetupData.secret }}</code>
                        <el-button size="mini" type="text" v-clipboard:copy="mfaSetupData.secret"
                          v-clipboard:success="onCopySuccess">
                          <i class="el-icon-document-copy"></i> 复制
                        </el-button>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>

            <div class="setup-actions">
              <el-button @click="goToMfaStep(1)">上一步</el-button>
              <el-button type="primary" @click="goToMfaStep(3)">下一步</el-button>
            </div>
          </div>

          <!-- 步骤三：验证 -->
          <div v-if="mfaSetupStep === 3" class="setup-step">
            <h3 class="section-subtitle">验证并完成设置</h3>
            <p class="section-description">
              请输入您的登录密码和身份验证器应用生成的6位验证码以完成设置。
            </p>

            <el-form :model="mfaVerifyForm" ref="mfaVerifyFormRef" :rules="mfaVerifyRules" class="mfa-form">
              <el-form-item prop="password">
                <el-input v-model="mfaVerifyForm.password" type="password" show-password placeholder="请输入登录密码"
                  prefix-icon="el-icon-lock"></el-input>
              </el-form-item>

              <el-form-item prop="code" class="verify-code-item">
                <div class="verify-code-label">身份验证器生成的6位验证码</div>
                <OtpInput v-model="mfaVerifyForm.code" :autoSubmit="true" :hasError="mfaCodeError"
                  :errorMessage="mfaCodeErrorMsg" :showExplanation="false" @complete="handleOtpComplete" />
              </el-form-item>
            </el-form>

            <div class="setup-actions">
              <el-button @click="goToMfaStep(2)">上一步</el-button>
              <el-button type="primary" @click="handleVerifyMfa" :loading="mfaVerifying">验证并启用</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作结果反馈 -->
      <MfaStatusFeedback v-else :status="mfaFeedbackStatus" :title="mfaFeedbackTitle" :message="mfaFeedbackMessage"
        @done="handleFeedbackDone" />
    </el-dialog>

    <!-- 禁用2FA 弹窗 -->
    <el-dialog title="禁用两步验证 (2FA)" :visible.sync="mfaDisableDialogVisible" width="650px"
      @closed="closeDisableMfaDialog" destroy-on-close custom-class="mfa-dialog">
      <div v-if="!mfaFeedbackStatus">
        <div class="disable-mfa-container" v-loading="mfaLoading">
          <div class="disable-warning">
            <i class="el-icon-warning"></i>
            <div class="warning-text">
              <h3>安全提醒</h3>
              <p>禁用两步验证将会降低您账号的安全性，确定要继续吗？</p>
            </div>
          </div>

          <p class="verification-text">为了确保是您本人操作，请输入您的登录密码和身份验证器应用生成的6位验证码。</p>

          <el-form :model="mfaDisableForm" ref="mfaDisableFormRef" :rules="mfaDisableRules" class="mfa-form">
            <el-form-item prop="password">
              <el-input v-model="mfaDisableForm.password" type="password" show-password placeholder="请输入登录密码"
                prefix-icon="el-icon-lock"></el-input>
            </el-form-item>

            <el-form-item prop="code" class="verify-code-item">
              <div class="verify-code-label">身份验证器生成的6位验证码</div>
              <OtpInput v-model="mfaDisableForm.code" :autoSubmit="true" :hasError="mfaCodeError"
                :errorMessage="mfaCodeErrorMsg" :showExplanation="false" @complete="handleDisableOtpComplete" />
            </el-form-item>
          </el-form>
        </div>

        <div class="setup-actions">
          <el-button @click="mfaDisableDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDisableMfa" :loading="mfaVerifying">确认禁用</el-button>
        </div>
      </div>

      <!-- 操作结果反馈 -->
      <MfaStatusFeedback v-else :status="mfaFeedbackStatus" :title="mfaFeedbackTitle" :message="mfaFeedbackMessage"
        @done="handleFeedbackDone">
        <template #actions v-if="mfaFeedbackStatus === 'success'">
          <el-button type="primary" @click="handleFeedbackDone">完成</el-button>
        </template>
      </MfaStatusFeedback>
    </el-dialog>

  </div>
</template>

<script>
import {
  getUserInfoApi, updateProfileApi, updatePasswordApi,
  getMyCommentApi, delMyCommentApi, getMyLikeApi, getMyReplyApi, getMyFeedbackApi, addFeedbackApi,
  signInApi, getSignInStatusApi, getSignInStatsApi
} from '@/api/user'
import { getMyArticleApi, likeArticleApi, delArticleApi } from '@/api/article'
import { getDictDataApi } from '@/api/dict'
import { getMyMoments, updateMoment, deleteMoment } from '@/api/moments'
import { uploadFileApi, deleteFileApi } from '@/api/file'
import { setupMfaApi, verifyMfaApi, disableMfaApi } from '@/api/auth'
import AvatarCropper from '@/components/common/AvatarCropper.vue'
import OtpInput from '@/components/common/OtpInput.vue'
import MfaStatusFeedback from '@/components/common/MfaStatusFeedback.vue'
import MfaGuide from '@/components/common/MfaGuide.vue'

import { marked } from "marked";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
  name: 'Profile',
  components: {
    AvatarCropper,
    Editor,
    Toolbar,
    OtpInput,
    MfaStatusFeedback,
    MfaGuide
  },
  data() {
    // 密码确认验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    // 验证邮箱格式
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }

    return {
      userInfo: {},
      editForm: {
        username: '',
        email: '',
        signature: ''
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      statistics: {
        posts: 0,
        likes: 0,
        followers: 0
      },
      // 点赞类型筛选
      likeType: 'all',
      currentTab: 'profile',
      tabs: [
        { key: 'profile', label: '个人资料', icon: 'fas fa-user' },
        { key: 'binding', label: '账号绑定', icon: 'fas fa-link' },
        { key: 'posts', label: '我的文章', icon: 'fas fa-file-alt' },
        { key: 'moments', label: '我的说说', icon: 'fas fa-comment-dots' },
        { key: 'comments', label: '我的评论', icon: 'fas fa-comments' },
        { key: 'replies', label: '我的回复', icon: 'fas fa-reply' },
        { key: 'likes', label: '我的点赞', icon: 'fas fa-heart' },
        { key: 'security', label: '账号安全', icon: 'fas fa-lock' },
        { key: 'feedback', label: '反馈', icon: 'fas fa-comment-dots' }
      ],
      boundAccounts: [
        {
          type: 'wechat',
          name: '微信公众号',
          icon: 'fab fa-weixin',
          isBound: true,
          username: 'wx_user123',
          color: '#10b981'
        },
        {
          type: 'qq',
          name: 'QQ',
          icon: 'fab fa-qq',
          isBound: false,
          color: '#60a5fa'
        },
        {
          type: 'gitee',
          name: '码云',
          icon: 'fab fa-git-alt',
          isBound: true,
          username: 'github_user',
          color: '#FF0000'
        }
      ],
      // 我的说说数据
      myMoments: [],
      momentTotal: 0,
      momentParams: {
        pageNum: 1,
        pageSize: 10
      },

      // 编辑说说相关
      momentDialogVisible: false,
      momentForm: {
        id: null,
        content: '',
        images: []
      },
      momentRules: {
        content: [
          { required: true, message: '请输入说说内容', trigger: 'blur' }
        ]
      },
      momentFileList: [],
      momentSubmitLoading: false,

      // 编辑器相关
      editor: null,
      editorConfig: {
        placeholder: '分享你的想法...',
        MENU_CONF: {
          uploadImage: {
            async customUpload(file, insertFn) {
              const formData = new FormData()
              formData.append('file', file)
              try {
                const res = await uploadFileApi(formData, 'moment')
                if (res.code === 200) {
                  insertFn(res.data, '', res.data)
                }
              } catch (error) {
                console.error(error)
              }
            }
          }
        }
      },

      // 图片预览
      previewVisible: false,
      previewUrl: '',

      // posts: [],
      // myComments: [],
      // myReplies: [],
      // myLikes: [],
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      // 个人资料表单
      profileForm: {
        nickname: '',
        email: '',
        sex: 2,
        signature: ''
      },
      profileRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      },
      params: {
        pageNum: 1,
        pageSize: 10,
        title: '',
      },
      total: 0,
      loading: false,
      // 添加反馈列表相关数据
      feedbackTypes: [],
      feedbackStatus: [],
      feedbackForm: {
        type: '',
        content: '',
        contact: ''
      },
      myFeedbacks: [],
      feedbackRules: {
        type: [
          { required: true, message: '请选择反馈类型', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入反馈内容', trigger: 'blur' },
        ],
        email: [
          { required: false, message: '请输入联系邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
        ],
      },
      signInStatus: false,
      signInStats: {
        continuousDays: 0,
        totalDays: 0
      },
      signInLoading: false,
      showCropper: false,
      // loading: false,
      // 我的文章
      posts: [],
      params: {
        pageNum: 1,
        pageSize: 10
      },
      // total: 0,
      // 我的评论
      myComments: [],

      // 我的回复
      myReplies: [],
      replyParams: {
        pageNum: 1,
        pageSize: 10
      },
      replyTotal: 0,

      // 我的点赞
      myLikes: [],
      likeType: 'all',
      likeParams: {
        pageNum: 1,
        pageSize: 10,
        type: null
      },
      likeTotal: 0,
      // MFA
      mfaEnableDialogVisible: false,
      mfaDisableDialogVisible: false,
      mfaSetupData: {
        qrCode: '',
        secret: ''
      },
      mfaVerifyForm: {
        code: '',
        password: '',
        secret: ''
      },
      mfaDisableForm: {
        code: '',
        password: ''
      },
      mfaLoading: false,
      mfaVerifying: false,
      mfaSetupStep: 1, // 2FA设置步骤
      mfaCodeError: false,
      mfaCodeErrorMsg: '',

      // 操作反馈状态
      mfaFeedbackStatus: '', // success, error, loading
      mfaFeedbackTitle: '',
      mfaFeedbackMessage: '',
      mfaVerifyRules: {
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入6位验证码',
          trigger: 'blur'
        }, {
          min: 6,
          max: 6,
          message: '请输入6位验证码',
          trigger: 'blur'
        }]
      },
      mfaDisableRules: {
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        code: [{
          required: true,
          message: '请输入6位验证码',
          trigger: 'blur'
        }, {
          min: 6,
          max: 6,
          message: '请输入6位验证码',
          trigger: 'blur'
        }]
      },
    }
  },

  watch: {
    '$store.state.userInfo': {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.$router.push('/')
        }
      },
      deep: true
    },
    currentTab(newVal, oldVal) {
      switch (newVal) {
        case 'posts':
          this.params.pageNum = 1
          this.getMyArticle()
          break
        case 'comments':
          this.params.pageNum = 1
          this.getMyComment()
          break
        case 'moments':
          this.momentParams.pageNum = 1
          this.getMyMoments()
          break
        case 'replies':
          this.params.pageNum = 1
          this.getMyReplies()
          break
        case 'likes':
          this.params.pageNum = 1
          this.getMyLikes()
          break
        case 'feedback':
          this.params.pageNum = 1
          this.getMyFeedbacks()
          break
        default:
          break
      }
    },
  },
  created() {
    getUserInfoApi().then(res => {
      this.userInfo = res.data.sysUser
      Object.assign(this.profileForm, res.data.sysUser)
    })

    this.getFeedbackDict()
    // 获取签到状态和统计
    this.getSignInStatus()
    this.getSignInStats()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy()
  },
  /* computed: {
    getAvatarUrl() {
      // 1. 首先尝试从localStorage获取缓存的Base64数据
      try {
        const avatarCache = localStorage.getItem('avatarCache');
        if (avatarCache) {
          const cache = JSON.parse(avatarCache);
          // 设置30天的缓存有效期
          const cacheValidityPeriod = 30 * 24 * 60 * 60 * 1000; // 30天毫秒数
          if (new Date().getTime() - cache.timestamp < cacheValidityPeriod) {
            return cache.data;
          }
        }
      } catch (e) {
        console.error('读取头像缓存失败:', e);
      }
      
      // 2. 如果没有有效的缓存，直接返回用户头像或默认头像
      return this.userInfo && this.userInfo.avatar 
        ? this.userInfo.avatar 
        : require('@/assets/images/King-over.png');
    }
  }, */
  methods: {
    onEditorCreated(editor) {
      this.editor = Object.seal(editor)
    },
    // 格式化时间方法
    /* formatTime(time) {
      return time ? formatRelativeTime(time) : '';
    }, */
    // 格式化相对时间
    formatRelativeTime(dateString) {
      if (!dateString) return '';

      const date = new Date(dateString);
      const now = new Date();
      const diffMs = now - date;
      const diffSec = Math.floor(diffMs / 1000);
      const diffMin = Math.floor(diffSec / 60);
      const diffHour = Math.floor(diffMin / 60);
      const diffDay = Math.floor(diffHour / 24);

      if (diffSec < 60) {
        return '刚刚';
      } else if (diffMin < 60) {
        return `${diffMin}分钟前`;
      } else if (diffHour < 24) {
        return `${diffHour}小时前`;
      } else if (diffDay < 30) {
        return `${diffDay}天前`;
      } else {
        // 超过30天显示具体日期
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }).replace(/\//g, '-');
      }
    },
    formatTime(time) {
      if (!time) return '';

      // 如果是ISO格式的时间字符串，转换为更友好的格式
      try {
        const date = new Date(time);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      } catch (e) {
        return time; // 如果转换失败，返回原始时间字符串
      }
    },
    // 预览图片方法
    // previewImage(images, index) {
    //   console.log('预览图片:', images, index);
    //   if (this.$refs.imagePreview) {
    //     this.$refs.imagePreview.show(images, index);
    //   }
    // },
    /**
     * 获取反馈类型字典
     */
    getFeedbackDict() {
      getDictDataApi(['feedback_type']).then(res => {
        this.feedbackTypes = res.data
      })

      getDictDataApi(['feedback_status']).then(res => {
        this.feedbackStatus = res.data
      })
    },
    /**
     * 获取我的评论
     */
    getMyComment() {
      this.loading = true
      getMyCommentApi(this.params).then(res => {
        this.myComments = res.data.records || [];
        this.total = res.data.total || 0;
      }).finally(() => {
        this.loading = false
      })
    },
    /**
     * 解析评论内容
     */
    parseContent(content) {
      return marked(content || "");
    },
    /**
     * 分页
     * @param val
     */
    handlePageChange(val) {
      this.params.pageNum = val
      this.getMyComment()
    },

    /**
     * 获取我的文章
     */
    getMyArticle() {
      this.loading = true
      getMyArticleApi(this.params).then(res => {
        this.posts = res.data.records || [];
        this.total = res.data.total || 0;
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * 跳转文章详情
     * @param id
     */
    viewPost(id) {
      // 获取当前文章
      const post = this.posts.find(p => p.id === id);

      // 如果是草稿状态，直接跳转到编辑页面
      if (post && post.status === 2) {
        this.$router.push(`/editor?id=${id}`);
        return;
      }

      // 正常发布的文章跳转到详情页
      this.$router.push(`/post/${id}`)
    },
    // 查看说说
    viewMoment(momentId) {
      this.$router.push(`/moments/${momentId}`);
    },
    // 处理点赞类型变化
    handleLikeTypeChange(type) {
      this.likeParams.pageNum = 1;
      this.likeParams.type = type === 'all' ? null : type;
      this.getMyLikes();
    },

    // 获取点赞类型标签
    getLikeTypeLabel(type) {
      const types = {
        'article': '文章点赞',
        'moment': '说说点赞',
        'comment': '评论点赞'
      };
      return types[type] || '点赞';
    },

    // 获取点赞类型标签样式
    getLikeTypeTag(type) {
      const types = {
        'article': 'primary',
        'moment': 'success',
        'comment': 'warning'
      };
      return types[type] || 'info';
    },
    // 取消点赞
    async cancelLike(id, type) {
      try {
        await this.$confirm('确定要取消点赞吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 根据不同类型调用不同的取消点赞API
        let res;
        if (type === 'article') {
          res = await cancelArticleLike(id);
        } else if (type === 'moment') {
          res = await cancelMomentLike(id);
        } else if (type === 'comment') {
          res = await cancelCommentLike(id);
        }

        if (res && res.code === 200) {
          this.$message.success('取消点赞成功');
          this.fetchLikes();
        } else {
          this.$message.error(res?.msg || '取消点赞失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消点赞失败:', error);
          this.$message.error('操作失败，请稍后重试');
        }
      }
    },
    /**
     * 编辑文章
     * @param id
     */
    editPost(id) {
      // 从localStorage中读取用户偏好的编辑器类型
      const preferredEditorType = localStorage.getItem('preferred-editor-type');
      // 构建编辑器URL，如果有用户偏好则添加editor_type参数
      let editorUrl = `/editor?id=${id}`;
      if (preferredEditorType && (preferredEditorType === 'markdown' || preferredEditorType === 'richtext')) {
        editorUrl += `&editor_type=${preferredEditorType}`;
      }
      this.$router.push(editorUrl);
    },
    /**
     * 删除文章
     * @param id
     */
    deletePost(row) {
      this.$confirm(`确定要删除标题为 '${row.title}' 的文章吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delArticleApi(row.id).then(res => {
          this.$message.success('删除成功')
          this.getMyArticle()
        }).catch(err => {
          this.$message.error(err.message || '删除失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      })
    },
    /**
     * 搜索文章
     * @param id
     */
    handleSearch() {
      this.params.pageNum = 1
      this.getMyArticle()
    },
    /**
     * 分页
     * @param val
     */
    handlePostChange(page) {
      this.params.pageNum = page
      this.getMyArticle()
    },
    /**
     * 绑定账号
     * @param type
     */
    bindAccount(type) {
      // 模拟绑定过程
      const account = this.boundAccounts.find(acc => acc.type === type)
      if (account) {
        this.$confirm('确定要绑定该账号吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          account.isBound = true
          this.$message.success('绑定成功')
        }).catch(() => {
          this.$message.info('已取消绑定');
        })
      }
    },
    unbindAccount(type) {
      const account = this.boundAccounts.find(acc => acc.type === type)
      if (account) {
        this.$confirm('确定要解除绑定吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          account.isBound = false
          this.$message.success('已解除绑定')
        }).catch(() => {
          this.$message.info('已取消解绑');
        })
      }
    },
    /**
     * 获取我的说说
     */
    getMyMoments() {
      if (this.loading) return; // 防止重复请求

      console.log('开始获取说说数据');
      this.loading = true;

      getMyMoments(this.momentParams).then(res => {
        console.log('获取到的说说数据:', res);
        if (res.code === 200 && res.data) {
          // 检查返回的数据结构
          console.log('返回的数据结构:', JSON.stringify(res.data));

          // 确保 records 存在并且是数组
          if (res.data.records && Array.isArray(res.data.records)) {
            this.myMoments = res.data.records;
            this.momentTotal = res.data.total || 0;
            console.log('处理后的说说数据:', this.myMoments);
          } else {
            console.error('返回的records不是数组:', res.data.records);
            this.myMoments = [];
            this.momentTotal = 0;
          }
        } else {
          this.$message.error(res.msg || '获取说说失败');
          this.myMoments = [];
          this.momentTotal = 0;
        }
      }).catch(err => {
        console.error('获取说说出错:', err);
        this.$message.error('获取说说失败，请稍后重试');
        this.myMoments = [];
        this.momentTotal = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    /* getMyMoments() {
      this.loading = true
      getMyMoments(this.momentParams).then(res => {
        if (res.code === 200) {
          this.myMoments = res.data.records || [];
          this.momentTotal = res.data.total || 0;
        } else {
          this.$message.error(res.msg || '获取说说失败')
        }
      }).finally(() => {
        this.loading = false
      })
    }, */



    /**
     * 说说分页变化
     */
    handleMomentPageChange(val) {
      this.momentParams.pageNum = val
      this.getMyMoments()
    },

    /**
     * 解析图片字符串为数组
     */
    parseImages(imagesStr) {
      console.log('解析图片字符串:', imagesStr);
      if (!imagesStr || imagesStr === '') return [];

      try {
        // 处理字符串格式的图片数据
        if (typeof imagesStr === 'string') {
          // 如果是JSON格式
          if (imagesStr.startsWith('[') && imagesStr.endsWith(']')) {
            const parsed = JSON.parse(imagesStr);
            return [...new Set(parsed)]; // 去重
          }

          // 如果是逗号分隔的字符串
          const images = imagesStr.split(',').filter(img => img && img.trim() !== '');
          return [...new Set(images)]; // 去重
        }

        // 如果已经是数组
        if (Array.isArray(imagesStr)) {
          return [...new Set(imagesStr)]; // 去重
        }

        return [];
      } catch (err) {
        console.error('解析图片失败:', err);
        return [];
      }
    },
    /* parseImages(imagesStr) {
     console.log('解析图片字符串:', imagesStr);
     if (!imagesStr || imagesStr === '') return [];
     try {
       if (typeof imagesStr === 'string') {
         // 尝试解析为JSON
         if (imagesStr.startsWith('[') && imagesStr.endsWith(']')) {
           return JSON.parse(imagesStr);
         }
         // 否则按逗号分隔
         return imagesStr.split(',').filter(img => img && img.trim() !== '');
       }
       return Array.isArray(imagesStr) ? imagesStr : [];
     } catch (err) {
       console.error('解析图片失败:', err);
       return [];
     }
   }, */
    // parseImages(images) {
    //   if (!images) return []
    //   return images.split(',').filter(img => img && img.trim() !== '')
    // },
    /**
     * 编辑说说
     */
    editMoment(moment) {
      this.momentForm = {
        id: moment.id,
        content: moment.content,
        images: this.parseImages(moment.images)
      }
      this.$nextTick(() => {
        if (this.editor) {
          this.editor.setHtml(moment.content)
        }
      })

      // 设置文件列表
      this.momentFileList = this.momentForm.images.map((url, index) => ({
        name: `图片${index + 1}`,
        url: url
      }))

      this.momentDialogVisible = true
    },

    /**
     * 删除说说确认
     */
    deleteMomentConfirm(id) {
      this.$confirm('确定要删除这条说说吗？删除后无法恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteMomentAction(id)
      }).catch(() => {
        this.$message.info('已取消删除');
      })
    },
    /**
     * 删除说说
     */
    deleteMomentAction(id) {
      deleteMoment(id).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getMyMoments()
        } else {
          this.$message.error(res.msg || '删除失败')
        }
      }).catch(err => {
        this.$message.error(err.message || '删除失败');
      })
    },

    /**
     * 重置说说表单
     */
    resetMomentForm() {
      this.momentForm = {
        id: null,
        content: '',
        images: []
      }
      if (this.editor) {
        this.editor.clear()
      }
      this.momentFileList = []
      if (this.$refs.momentFormRef) {
        this.$refs.momentFormRef.resetFields()
      }
    },
    /**
     * 上传说说图片
     */
    async uploadMomentImage(options) {
      const { file } = options

      // 检查文件大小
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB')
        return
      }

      // 检查文件类型
      const isImage = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'].includes(file.type)
      if (!isImage) {
        this.$message.error('只能上传jpg/jpeg/png/gif格式的图片')
        return
      }

      const formData = new FormData()
      formData.append('file', file)

      try {
        const res = await uploadFileApi(formData, 'moment')
        if (res.code === 200) {
          this.momentForm.images.push(res.data)
          this.momentFileList.push({
            name: file.name,
            url: res.data
          })
          this.$message.success('上传成功')
        } else {
          this.$message.error(res.msg || '上传失败')
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        this.$message.error('上传失败')
      }
    },

    /**
     * 移除说说图片
     */
    handleRemoveMomentImage(file, fileList) {
      const index = this.momentForm.images.indexOf(file.url)
      if (index !== -1) {
        this.momentForm.images.splice(index, 1)
      }
      this.momentFileList = fileList
    },

    /**
     * 预览上传的图片
     */
    // handlePreviewMomentImage(file) {
    //   this.previewUrl = file.url
    //   this.previewVisible = true
    // },
    handlePreviewMomentImage(file) {
      console.log('预览上传图片:', file);
      if (this.$refs.imagePreview) {
        this.$refs.imagePreview.show([file.url], 0);
      } else {
        this.previewUrl = file.url;
        this.previewVisible = true;
      }
    },
    /**
     * 超出图片上传限制
     */
    handleExceedMomentImage(files, fileList) {
      this.$message.warning(`最多只能上传9张图片，本次选择了 ${files.length} 张图片，共选择了 ${files.length + fileList.length} 张图片`)
    },

    /**
     * 预览图片
     */
    previewImage(images, index) {
      this.previewUrl = images[index]
      this.previewVisible = true
      if (this.$refs.imagePreview) {
        this.$refs.imagePreview.show(images, index);
      }
    },
    /**
     * 提交编辑说说
     */
    submitMomentEdit() {
      this.$refs.momentFormRef.validate(async valid => {
        if (!valid) return

        this.momentSubmitLoading = true
        try {
          const newContent = this.editor.getHtml()
          // 将图片数组转为逗号分隔的字符串
          const submitData = {
            id: this.momentForm.id,
            content: newContent,
            images: this.momentForm.images.join(',')
          }

          const res = await updateMoment(submitData)
          if (res.code === 200) {
            this.$message.success('更新成功')
            this.momentDialogVisible = false
            // 重新加载说说列表 刷新列表以获取更新后的数据
            this.getMyMoments()
          } else {
            this.$message.error(res.msg || '更新失败')
          }
        } catch (error) {
          console.error('更新说说失败:', error)
          this.$message.error('更新失败')
        } finally {
          this.momentSubmitLoading = false
        }
      })
    },
    /**
     * 删除评论
     */
    // 删除评论
    deleteComment(id) {
      this.$confirm('确定要删除这条评论吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMyCommentApi(id).then(res => {
          this.$message.success('删除成功');
          // 根据当前标签页刷新数据
          if (this.currentTab === 'comments') {
            this.getMyComment();
          } else if (this.currentTab === 'replies') {
            this.getMyReplies();
          }
        }).catch(err => {
          this.$message.error(err.message || '删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // deleteComment(id) {
    //   this.$confirm('此操作会把该评论下的子评论也一并删除，是否继续？', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     delMyCommentApi(id).then(res => {
    //       this.$message.success('删除成功')
    //       this.getMyComment()
    //     })
    //   }).catch(() => { })
    // },
    /**
     * 删除回复
     */
    deleteReply(id) {
      this.$confirm('确定要删除这条回复吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMyCommentApi(id).then(res => {
          this.$message.success('删除成功')
          this.getMyReplies()
        }).catch(err => {
          this.$message.error(err.message || '删除失败');
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      })
    },
    /**
     * 取消点赞
     * @param id
     */
    cancelLike(id) {
      this.$confirm('确定要取消点赞吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        likeArticleApi(id).then(res => {
          this.$message.success('已取消点赞')
          this.getMyLikes()
        }).catch(err => {
          this.$message.error(err.message || '操作失败');
        })
      }).catch(() => {
        this.$message.info('已取消操作');
      })
    },

    /**
     * 添加反馈
     */
    submitFeedback() {
      this.$refs.feedbackForm.validate(valid => {
        if (valid) {
          this.loading = true
          addFeedbackApi(this.feedbackForm).then(res => {
            this.$message.success('感谢您的反馈！')
            this.feedbackForm = { ...{} }
            this.$refs.feedbackForm.resetFields();
          }).catch(err => {
            this.$message.error(err.message || '提交失败');
          }).finally(() => {
            this.loading = false
          })
        }
      })

    },
    // 提交密码修改
    submitPasswordChange() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          updatePasswordApi(this.passwordForm).then(res => {
            this.$message.success('密码修改成功！')
            this.$refs.passwordForm.resetFields()
          }).catch(err => {
            this.$message.error(err.message || '密码修改失败')
          }).finally(() => {
            this.loading = false

          })
        }
      })
    },
    // 提交个人资料
    submitProfile() {
      this.loading = true
      updateProfileApi(this.profileForm).then(res => {
        this.userInfo.nickname = this.profileForm.nickname
        this.$store.state.userInfo.nickname = this.profileForm.nickname
        this.$message.success('个人资料更新成功！')
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 重置个人资料
    resetProfile() {
      this.profileForm = { ...this.userInfo }
      this.$message.info('已重置个人资料');
    },
    /**
     * 获取我的回复
     */
    getMyReplies() {
      this.loading = true;
      getMyReplyApi(this.replyParams).then(res => {
        this.myReplies = res.data.records || [];
        this.replyTotal = res.data.total || 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    // getMyReplies() {
    //   this.loading = true
    //   getMyReplyApi(this.params).then(res => {
    //     this.myReplies = res.data.records
    //     this.total = res.data.total
    //   }).finally(() => {
    //     this.loading = false
    //   })
    // },
    /**
     * 回复分页
     */
    handleReplyPageChange(val) {
      this.params.pageNum = val
      this.getMyReplies()
    },
    /**
     * 获取我的点赞
     */
    // 获取我的点赞
    getMyLikes() {
      this.loading = true;
      const params = { ...this.likeParams };
      if (params.type === null) {
        delete params.type;
      }

      getMyLikeApi(params).then(res => {
        this.myLikes = res.data.records || [];
        this.likeTotal = res.data.total || 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    /* getMyLikes() {
      this.loading = true
      getMyLikeApi(this.params).then(res => {
        this.myLikes = res.data.records
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    }, */
    /**
     * 点赞分页
     */
    handleLikePageChange(val) {
      this.params.pageNum = val
      this.getMyLikes()
    },
    /**
     * 获取我的反馈列表
     */
    getMyFeedbacks() {
      this.loading = true
      let params = {
        ...this.params,
        source: 'PC'
      }
      getMyFeedbackApi(params).then(res => {
        this.myFeedbacks = res.data.records
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * 反馈列表分页
     */
    handleFeedbackPageChange(val) {
      this.params.pageNum = val
      this.getMyFeedbacks()
    },
    /**
     * 获取签到状态
     */
    getSignInStatus() {
      getSignInStatusApi().then(res => {
        this.signInStatus = res.data
      })
    },

    /**
     * 获取签到统计
     */
    getSignInStats() {
      getSignInStatsApi().then(res => {
        this.signInStats = res.data
      })
    },

    /**
     * 签到
     */
    handleSignIn() {
      if (this.signInStatus.hasSignedIn) return

      this.signInLoading = true
      signInApi().then(res => {
        this.$message.success('签到成功！')
        this.getSignInStatus()
        this.getSignInStats()
      }).catch(err => {
        this.$message.error(err.message || '签到失败')
      }).finally(() => {
        this.signInLoading = false
      })
    },

    /**
     * 更新头像
     */
    handleAvatarUpdate(newAvatarUrl) {
      this.userInfo.avatar = newAvatarUrl;
      // 如果有缓存的blob URL，尝试释放它
      // if (this.userInfo.avatarBlobUrl && this.userInfo.avatarBlobUrl.startsWith('blob:')) {
      //   URL.revokeObjectURL(this.userInfo.avatarBlobUrl);
      // }
      // 更新vuex中的头像
      // this.$store.commit('SET_AVATAR', newAvatarUrl);
    },
    /**
     * 异步加载OSS头像并缓存
     */
    /* loadOssAvatar(url) {
     // 创建一个隐藏的图片元素来加载OSS图片
     const img = new Image();
     img.crossOrigin = 'anonymous';
     
     img.onload = () => {
       // 图片加载成功，转换为Base64并缓存
       const canvas = document.createElement('canvas');
       canvas.width = img.width;
       canvas.height = img.height;
       
       const ctx = canvas.getContext('2d');
       ctx.drawImage(img, 0, 0);
       
       try {
         const base64data = canvas.toDataURL('image/png');
         const cacheData = {
           data: base64data,
           timestamp: new Date().getTime()
         };
         localStorage.setItem('avatarCache', JSON.stringify(cacheData));
       } catch (e) {
         console.error('缓存头像失败:', e);
       }
     };
     
     // 添加随机参数避免缓存
     const timestamp = new Date().getTime();
     img.src = url.includes('?') ? `${url}&t=${timestamp}` : `${url}?t=${timestamp}`;
   }, */

    // --- MFA Methods ---
    // 复制成功提示
    onCopySuccess() {
      this.$message.success('密钥已复制到剪贴板');
    },

    // 跳转到指定MFA设置步骤
    goToMfaStep(step) {
      this.mfaSetupStep = step;
      this.mfaCodeError = false;
      this.mfaCodeErrorMsg = '';
    },

    // 处理验证码输入完成 - 启用2FA
    handleOtpComplete(code) {
      if (this.mfaVerifyForm.password) {
        this.handleVerifyMfa();
      }
    },

    // 处理验证码输入完成 - 禁用2FA
    handleDisableOtpComplete(code) {
      if (this.mfaDisableForm.password) {
        this.handleDisableMfa();
      }
    },

    // 处理反馈完成
    handleFeedbackDone() {
      if (this.mfaEnableDialogVisible) {
        this.closeEnableMfaDialog();
      } else if (this.mfaDisableDialogVisible) {
        this.closeDisableMfaDialog();
      }
    },

    // 打开启用2FA弹窗
    openEnableMfaDialog() {
      this.mfaEnableDialogVisible = true;
      this.mfaFeedbackStatus = '';
      this.mfaLoading = true;

      setupMfaApi().then(res => {
        this.mfaSetupData = res.data;
        this.mfaVerifyForm.secret = res.data.secret;
      }).catch(err => {
        this.mfaFeedbackStatus = 'error';
        this.mfaFeedbackTitle = '获取2FA信息失败';
        this.mfaFeedbackMessage = err.message || '请稍后重试，或联系客服处理';
      }).finally(() => {
        this.mfaLoading = false;
      });
    },

    // 关闭启用2FA弹窗
    closeEnableMfaDialog() {
      this.mfaEnableDialogVisible = false;
      this.mfaSetupData = {
        qrCode: '',
        secret: ''
      };
      this.mfaSetupStep = 1;
      this.mfaFeedbackStatus = '';
      this.mfaCodeError = false;
      this.mfaCodeErrorMsg = '';

      if (this.$refs.mfaVerifyFormRef) {
        this.$refs.mfaVerifyFormRef.resetFields();
      }
    },

    // 验证并启用2FA
    handleVerifyMfa() {
      this.$refs.mfaVerifyFormRef.validate(valid => {
        if (valid) {
          this.mfaVerifying = true;
          this.mfaCodeError = false;

          verifyMfaApi(this.mfaVerifyForm).then(() => {
            // 显示成功反馈
            this.mfaFeedbackStatus = 'success';
            this.mfaFeedbackTitle = '两步验证已成功启用';
            this.mfaFeedbackMessage = '您的账户现已受到额外的安全保护。下次登录时，您将需要输入验证码。';

            // 更新用户信息
            this.userInfo.mfaEnabled = true;
          }).catch(err => {
            // 显示验证码错误
            this.mfaCodeError = true;
            this.mfaCodeErrorMsg = err.message || '验证失败，请检查验证码是否正确';
          }).finally(() => {
            this.mfaVerifying = false;
          });
        }
      });
    },

    // 打开禁用2FA弹窗
    openDisableMfaDialog() {
      this.mfaDisableDialogVisible = true;
      this.mfaFeedbackStatus = '';
      this.mfaCodeError = false;
      this.mfaCodeErrorMsg = '';
    },

    // 关闭禁用2FA弹窗
    closeDisableMfaDialog() {
      this.mfaDisableDialogVisible = false;
      this.mfaFeedbackStatus = '';

      if (this.$refs.mfaDisableFormRef) {
        this.$refs.mfaDisableFormRef.resetFields();
      }
    },

    // 禁用2FA
    handleDisableMfa() {
      this.$refs.mfaDisableFormRef.validate(valid => {
        if (valid) {
          this.mfaVerifying = true;
          this.mfaCodeError = false;

          disableMfaApi(this.mfaDisableForm).then(() => {
            // 显示成功反馈
            this.mfaFeedbackStatus = 'success';
            this.mfaFeedbackTitle = '两步验证已禁用';
            this.mfaFeedbackMessage = '您的账户已不再使用两步验证保护。建议您保持良好的密码习惯，以确保账户安全。';

            // 更新用户信息
            this.userInfo.mfaEnabled = false;
          }).catch(err => {
            // 显示验证码错误
            this.mfaCodeError = true;
            this.mfaCodeErrorMsg = err.message || '验证失败，请检查验证码是否正确';
          }).finally(() => {
            this.mfaVerifying = false;
          });
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
:deep(input[aria-hidden=true]) {
  display: none !important;
}

.delete {
  color: red;
}

.editor-container {
  border: 1px solid #ccc;
  z-index: 100;
}

.profile-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  min-height: 100vh;
}

.profile-sidebar {
  position: sticky;
  top: 80px;
  height: fit-content;
  width: 300px;
  flex-shrink: 0;


  @include responsive(sm) {
    position: unset;

    .el-dialog {
      width: 95% !important;
    }
  }
}

.like-type-selector {
  margin-bottom: 16px;
}

/* 点赞项样式 */
.like-item {
  margin-bottom: 16px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  }

  /* 文章点赞项样式 */
  .article-like-content {
    display: flex;
    flex-direction: column;

    .article-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0 0 12px 0;
      line-height: 1.4;

      .el-link {
        font-size: 18px;
        font-weight: 600;
      }
    }

    .article-summary {
      font-size: 14px;
      color: #606266;
      margin: 0 0 16px 0;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  /* 说说点赞项样式 */
  .moment-like-content {
    display: flex;
    flex-direction: column;

    .moment-content {
      margin-bottom: 16px;

      p {
        font-size: 15px;
        color: #303133;
        margin: 0;
        line-height: 1.6;
      }
    }
  }

  /* 评论点赞项样式 */
  .comment-like-content {
    display: flex;
    flex-direction: column;

    .comment-content {
      margin-bottom: 12px;

      p {
        font-size: 15px;
        color: #303133;
        margin: 0;
        line-height: 1.6;
      }
    }

    .comment-source {
      margin-bottom: 16px;
      font-size: 14px;
    }
  }

  /* 元信息样式 */
  .like-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .el-tag {
      display: flex;
      align-items: center;

      i {
        margin-right: 4px;
      }
    }
  }
}

/* 暗色模式适配 */
@media (prefers-color-scheme: dark) {
  .like-item {
    .article-like-content {
      .article-summary {
        color: #bbb;
      }
    }

    .moment-like-content {
      .moment-content p {
        color: #e0e0e0;
      }
    }

    .comment-like-content {
      .comment-content p {
        color: #e0e0e0;
      }
    }
  }
}

/* 自定义暗色模式类 */
.dark-mode {
  .like-item {
    .article-like-content {
      .article-summary {
        color: #bbb;
      }
    }

    .moment-like-content {
      .moment-content p {
        color: #e0e0e0;
      }
    }

    .comment-like-content {
      .comment-content p {
        color: #e0e0e0;
      }
    }
  }
}

.like-item {
  margin-bottom: 16px;

  .like-content {
    .like-actions {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;

      .like-title {
        font-size: 15px;
        font-weight: 500;
      }

      .like-comment {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .comment-source {
          font-size: 12px;
          margin-top: 4px;
          margin-left: 4px;
        }
      }
    }

    .like-meta {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.comment-meta,
.reply-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

// 说说项样式
.moment-item {
  margin-bottom: 16px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }

  .moment-content {
    cursor: pointer;

    .moment-text {
      font-size: 15px;
      line-height: 1.6;
      margin-bottom: 12px;
      white-space: pre-wrap;
      word-break: break-word;
    }

    /* .moment-meta {
      display: flex;
      gap: 8px;
      margin-top: 12px;
    } */
    .moment-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 12px;

      .time-tag {
        .time-tag-item {
          &.el-tag--warning {
            background-color: #fdf6ec;
            color: #e6a23c;
            border-color: #faecd8;
          }

          &.el-tag--info {
            background-color: #f4f4f5;
            color: #909399;
            border-color: #e9e9eb;
          }

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          }

          transition: all 0.3s ease;
        }
      }

      .el-tag {
        display: flex;
        align-items: center;
        border-radius: 4px;
        padding: 0 8px;
        height: 24px;

        &.el-tag--success {
          background-color: #f0f9eb;
          color: #67c23a;
          border-color: #e1f3d8;
        }

        &.el-tag--primary {
          background-color: #ecf5ff;
          color: #409eff;
          border-color: #d9ecff;
        }

        i {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }
  }

  .moment-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
    border-top: 1px solid #f0f0f0;
    padding-top: 12px;

    .delete {
      color: #f56c6c;
    }
  }

  // 图片网格样式
  .moment-images {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    margin-top: 12px;

    .image-container {
      position: relative;
      width: 100%;
      padding-top: 100%; // 1:1 比例
      overflow: hidden;
      border-radius: 4px;
      background-color: #f5f5f5;
      cursor: zoom-in;

      img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover; // 保持比例填充
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }
  }
}


// 上传图片组件样式
.upload-images {
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
    background-color: #fafafa;

    &:hover {
      border-color: var(--primary);
      color: var(--primary);
    }
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
    border-radius: 8px;
  }
}

// 上传提示样式
.upload-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 10px;
  color: #909399;
  font-size: 13px;

  i {
    color: #409EFF;
  }
}

// 弹窗样式
:deep(.moment-dialog) {
  border-radius: 12px;
  overflow: hidden;

  .el-dialog__header {
    background: #f8f9fa;
    padding: 16px 20px;
    border-bottom: 1px solid #ebeef5;

    .el-dialog__title {
      font-weight: 600;
      font-size: 18px;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
  }

  .moment-textarea {
    .el-textarea__inner {
      border-radius: 8px;
      padding: 12px;
      font-size: 15px;

      &:focus {
        border-color: var(--primary);
      }
    }
  }
}

// 预览弹窗样式
:deep(.preview-dialog) {
  .el-dialog__body {
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #000;

    img {
      max-width: 100%;
      max-height: 80vh;
      object-fit: contain;
    }
  }
}

.user-card {
  text-align: center;
  background: var(--card-bg);
  border: var(--border-color);

  .avatar-section {
    margin-bottom: 16px;
  }

  .avatar-wrapper {
    width: 100px;
    height: 100px;
    margin: 0 auto;
    position: relative;
    cursor: pointer;
    border-radius: 50%;
    overflow: hidden;

    .upload-overlay {
      position: absolute;
      inset: 0;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.3s;

      i {
        font-size: 24px;
        color: white;
      }
    }

    &:hover .upload-overlay {
      opacity: 1;
    }
  }

  .username {
    font-size: 18px;
    font-weight: 600;
    margin: 0 0 8px;
    color: var(--text-primary);
  }

  .signature {
    color: var(--text-secondary);
    font-size: 14px;
    margin: 0 0 16px;
    line-height: 1.5;
  }

  .user-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    padding-top: 16px;
    border-top: 1px solid var(--border-color);

    .stat-item {
      .number {
        display: block;
        font-size: 18px;
        font-weight: 600;
        color: var(--primary-color);
      }

      .label {
        font-size: 12px;
        color: var(--text-secondary);
      }
    }
  }
}

.el-menu-item {
  color: var(--text-secondary) !important;
}

.nav-menu {
  border-radius: 8px;
  background: var(--card-bg);
  border-right: none;
  margin-top: $spacing-md;


  .is-active {
    background: var(--hover-bg);
    color: $primary;
  }

  :deep(.el-menu-item) {
    height: 48px;
    line-height: 48px;

    &:hover {
      background: var(--hover-bg);
      color: $primary;
    }

    i {
      margin-right: 12px;
    }
  }
}

.content-area {
  flex: 1;
  min-width: 0;
  background: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
  color: var(--text-primary);
}

/* 确保预览层在最上层 */
.preview-layer {
  position: fixed;
  z-index: 9999;
  /* 确保在对话框之上 */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 修改对话框样式，确保不会覆盖预览 */
:deep(.el-dialog) {
  z-index: 2000;
  /* 低于预览层 */
}

/* 修复点赞列表的样式问题 */
.likes-list {
  margin-top: 10px;
  min-height: auto;
  /* 移除最小高度限制 */

  .empty-placeholder {
    padding: 20px 0;
    text-align: center;
    color: #909399;
  }

  .like-item {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }
}

/* 确保内容区域有合适的内边距 */
.content-section {
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 标签页内容区域样式 */
.el-tab-pane {
  padding-top: 10px;
}

.profile-form,
.security-form,
.feedback-form {
  max-width: 600px;
}

.post-item {
  margin-bottom: 16px;

  .post-content {
    margin-bottom: 16px;
  }

  .post-title {
    font-size: 18px;
    color: var(--text-secondary);
    margin: 0 0 12px;
    cursor: pointer;

    &:hover {
      color: $primary;
    }
  }

  .post-excerpt {
    color: var(--text-secondary);
    margin: 0 0 12px;
    line-height: 1.5;
  }

  .post-meta {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;

    .el-tag {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .post-actions {
    display: flex;
    gap: 16px;
    justify-content: flex-end;
    padding-top: 16px;
    border-top: 1px solid var(--border-color);
  }
}

.comment-item,
.reply-item,
.like-item {
  margin-bottom: 16px;

  .comment-actions,
  .reply-actions,
  .like-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    .article-title {
      font-size: 18px;
      font-weight: 700;
    }
  }

  .comment-text,
  .reply-text {
    color: var(--text-secondary);
    margin: 0 0 12px;
    line-height: 1.5;

    :deep(img) {
      max-width: 200px !important;
      max-height: 200px !important;
    }
  }

  .comment-meta,
  .reply-meta,
  .like-meta {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}



.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.binding-item {
  margin-bottom: 16px;

  .account-info {
    display: flex;
    align-items: center;
    gap: 16px;

    i {
      font-size: 24px;
      color: var(--primary-color);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-container {
    flex-direction: column;
  }

  .profile-sidebar {
    width: 100%;
  }

  .content-area {
    padding: 16px;
  }

  .action-bar {
    .el-input {
      width: 100% !important;
    }
  }
}

.hidden-input {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

.binding-item,
.comment-item,
.reply-item,
.like-item,
.post-item {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
}


.binding-tips {
  margin-bottom: 24px;

  :deep(.el-alert) {
    border-radius: 8px;

    .el-alert__title {
      font-size: 15px;
      font-weight: 500;
    }

    .el-alert__description {
      margin: 8px 0 0;
      font-size: 13px;
      color: var(--text-secondary);
    }
  }
}

.binding-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;

  .binding-item {
    .binding-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px;
    }

    .account-info {
      display: flex;
      align-items: center;
      gap: 16px;
    }

    .account-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--hover-bg);
      transition: all 0.3s ease;

      i {
        font-size: 24px;
        color: var(--primary-color);
      }
    }

    .account-details {
      display: flex;
      flex-direction: column;
      gap: 4px;
    }

    .account-name {
      font-size: 16px;
      font-weight: 500;
      color: var(--text-primary);
    }

    .account-desc {
      font-size: 13px;
      color: var(--text-secondary);
    }

    .binding-status {
      display: flex;
      align-items: center;
      gap: 16px;

      .status-tag {
        min-width: 64px;
        text-align: center;
      }
    }

    &:hover {
      .account-icon {
        transform: scale(1.05);
        background: var(--primary-color);

        i {
          color: $primary;
        }
      }
    }
  }
}

.feedback-list {
  .feedback-item {
    margin-bottom: 16px;

    .feedback-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .feedback-info {
        display: flex;
        align-items: center;
        gap: 12px;

        .feedback-time {
          display: flex;
          align-items: center;
          gap: 5px;
          color: var(--text-secondary);
          font-size: 14px;

        }
      }
    }

    .feedback-content {
      color: var(--text-primary);
      line-height: 1.6;
      margin-bottom: 16px;
    }

    .feedback-reply {
      background: var(--hover-bg);
      padding: 12px;
      border-radius: 8px;

      .reply-title {
        color: var(--text-secondary);
        font-weight: 500;
        margin-bottom: 8px;

        i {
          margin-right: 4px;
        }
      }

      .reply-content {
        color: var(--text-secondary);
        margin: 0;
        line-height: 1.6;
      }
    }
  }
}

.posts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .write-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 4px;
    background: $primary;
    color: white;
    text-decoration: none;
    transition: all 0.3s ease;

    &:hover {
      background: darken($primary, 10%);
    }

    i {
      font-size: 14px;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: var(--text-secondary);

  i {
    font-size: 48px;
    margin-bottom: 16px;
  }

  p {
    margin-bottom: 24px;
  }

  .btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 24px;
    border-radius: 4px;
    background: var(--hover-bg);
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s ease;

    &:hover {
      background: var(--hover-bg-dark);
    }

    &.primary {
      background: $primary;
      color: white;

      &:hover {
        background: darken($primary, 10%);
      }
    }
  }
}

.sign-in-section {
  padding: 16px 0;
  border-top: 1px solid var(--border-color);
  border-bottom: 1px solid var(--border-color);
  margin: 16px 0;

  .sign-in-stats {
    display: flex;
    justify-content: center;
    gap: 24px;
    margin-top: 16px;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;

      .label {
        font-size: 12px;
        color: var(--text-secondary);
      }

      .value {
        font-size: 16px;
        font-weight: 600;
        color: var(--primary-color);
      }
    }
  }
}

.security-section {
  margin-bottom: 24px;

  .sub-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
  }

  .mfa-status-card {
    display: flex;
    align-items: center;
    padding: 16px;
    border-radius: 8px;
    gap: 16px;

    &.enabled {
      background-color: #f0f9eb;
      border: 1px solid #e1f3d8;
    }

    &.disabled {
      background-color: #fef0f0;
      border: 1px solid #fde2e2;
    }

    .status-icon {
      font-size: 24px;
    }

    &.enabled .status-icon {
      color: #67c23a;
    }

    &.disabled .status-icon {
      color: #f56c6c;
    }

    .status-text {
      flex-grow: 1;

      .status-title {
        font-weight: 500;
        margin: 0 0 4px 0;
      }

      .status-desc {
        font-size: 13px;
        color: #909399;
        margin: 0;
      }
    }
  }
}

:deep(.mfa-dialog) {
  .el-dialog__body {
    padding: 20px 25px;
  }

  .secret-key {
    word-break: break-all;
    font-family: monospace;
    font-size: 14px;
    background: var(--bg-light, #f5f7fa);
    padding: 10px;
    border-radius: 4px;
    display: inline-block;
    margin: 0;
  }

  .secret-key-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10px;
    background: var(--bg-light, #f5f7fa);
    padding: 10px 16px;
    border-radius: 4px;
  }

  .setup-step {
    animation: fadeIn 0.3s ease;
  }

  .setup-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid var(--border-color, #EBEEF5);
  }

  .section-subtitle {
    font-size: 18px;
    font-weight: 600;
    margin: 0 0 16px;
    color: var(--text-primary, #303133);
  }

  .section-description {
    margin: 0 0 24px;
    color: var(--text-secondary, #606266);
    line-height: 1.6;
  }

  .qr-code-section {
    margin-bottom: 24px;
  }

  .qr-code-container {
    display: flex;
    justify-content: center;
    margin: 24px 0;

    .qr-code-image {
      width: 220px;
      height: 220px;
      border: 1px solid var(--border-color, #EBEEF5);
      padding: 10px;
      border-radius: 8px;
      background: white;
    }
  }

  .manual-entry {
    .el-collapse {
      border: none;

      .el-collapse-item__header {
        color: var(--primary-color, #409EFF);
        font-weight: 500;
        background: transparent;
        border: none;
        padding: 0;

        &:hover {
          color: var(--primary-color-light, #66b1ff);
        }
      }

      .el-collapse-item__wrap {
        border: none;
        background: transparent;
      }

      .el-collapse-item__content {
        padding: 16px 0 0;
      }
    }

    .manual-key {
      background: var(--bg-light, #f5f7fa);
      border-radius: 8px;
      padding: 16px;

      p {
        margin: 0 0 12px;
        color: var(--text-secondary, #606266);
      }
    }
  }

  .mfa-form {
    max-width: 100%;
    margin: 24px 0;

    .verify-code-item {
      margin-top: 24px;
    }

    .verify-code-label {
      margin-bottom: 16px;
      font-size: 14px;
      color: var(--text-secondary, #606266);
    }
  }

  .disable-mfa-container {
    padding: 0 0 16px;

    .disable-warning {
      display: flex;
      align-items: flex-start;
      background: #fff8f0;
      border-left: 4px solid #e6a23c;
      padding: 16px;
      border-radius: 4px;
      margin-bottom: 24px;

      i {
        font-size: 24px;
        color: #e6a23c;
        margin-right: 16px;
      }

      .warning-text {
        h3 {
          margin: 0 0 8px;
          font-size: 16px;
          color: #e6a23c;
        }

        p {
          margin: 0;
          color: var(--text-secondary, #606266);
          line-height: 1.6;
        }
      }
    }

    .verification-text {
      margin: 0 0 24px;
      color: var(--text-secondary, #606266);
      line-height: 1.6;
    }
  }
}

// 动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 暗色模式适配
@media (prefers-color-scheme: dark) {
  :deep(.mfa-dialog) {

    .secret-key,
    .secret-key-wrapper {
      background: rgba(255, 255, 255, 0.05);
    }

    .section-subtitle {
      color: var(--text-primary-dark, #e0e0e0);
    }

    .section-description,
    .verification-text,
    .verify-code-label {
      color: var(--text-secondary-dark, #a0a0a0);
    }

    .qr-code-image {
      background: #fff;
      border-color: var(--border-color-dark, #4c4c4c);
    }

    .manual-key {
      background: rgba(255, 255, 255, 0.05);

      p {
        color: var(--text-secondary-dark, #a0a0a0);
      }
    }

    .disable-warning {
      background: rgba(230, 162, 60, 0.1);
      border-color: #e6a23c;

      .warning-text p {
        color: var(--text-secondary-dark, #a0a0a0);
      }
    }
  }
}

.dark-mode {
  :deep(.mfa-dialog) {

    .secret-key,
    .secret-key-wrapper {
      background: rgba(255, 255, 255, 0.05);
    }

    .section-subtitle {
      color: var(--text-primary-dark, #e0e0e0);
    }

    .section-description,
    .verification-text,
    .verify-code-label {
      color: var(--text-secondary-dark, #a0a0a0);
    }

    .qr-code-image {
      background: #fff;
      border-color: var(--border-color-dark, #4c4c4c);
    }

    .manual-key {
      background: rgba(255, 255, 255, 0.05);

      p {
        color: var(--text-secondary-dark, #a0a0a0);
      }
    }

    .disable-warning {
      background: rgba(230, 162, 60, 0.1);
      border-color: #e6a23c;

      .warning-text p {
        color: var(--text-secondary-dark, #a0a0a0);
      }
    }
  }
}

.security-form {
  max-width: 600px;
}
</style>
